<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\common\model\cloud;

use buwang\base\BaseModel;

class Wallet extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'cloud_wallet';

    public static function changeAmount($member_id, $service_id, $type, $amount, $memo)
    {
        if ($amount == 0) return self::setError('变更数量不能为0');
        if (!in_array($type, ['buy', 'use'])) return self::setError('变更类型有误');

        $wallet = self::where(['member_id' => $member_id, 'service_id' => $service_id])->find();

        if (!$wallet && $type != 'buy') return self::setError('未购买该服务');

        //无次数记录时新建记录
        if (!$wallet) $before = 0;
        else $before = $wallet['amount'];

        $value = $amount;
        $after = bcadd($before, $value);

        if ($after < 0) return self::setError('剩余次数不足');

        //变更次数
        if (!$wallet) {
            $walletParam = [
                'member_id' => $member_id,
                'service_id' => $service_id,
                'amount' => $after,
                'total' => $after,
            ];
            self::create($walletParam);
        } else {
            $wallet->amount = $after;
            if ($type == 'buy') $wallet->total = bcadd($wallet['total'], $value);
            $wallet->save();
        }

        //增记录
        WalletBill::create(compact('member_id', 'service_id', 'type', 'value', 'before', 'after', 'memo'));

        return true;
    }
}